package com.akk.business;

import com.akk.PayConstants;
import com.akk.common.enums.Enums;
import com.akk.module.access.entity.AccessBind;
import com.akk.module.access.service.AccessService;
import com.akk.module.avs.entity.AvsCustomer;
import com.akk.module.avs.entity.AvsPayOrder;
import com.akk.module.avs.service.AvsCustomerService;
import com.akk.module.avs.service.AvsPayOrderService;
import com.akk.module.cjpay.model.CJpayBindCardQueryRequest;
import com.akk.module.cjpay.model.CjpayBindCardRequest;
import com.akk.module.cjpay.model.CjpayDirectPaymentRequest;
import com.akk.module.cjpay.model.CjpayNotifyRequest;
import com.akk.module.cjpay.service.CjPayService;
import com.akk.module.cjpay.utils.ChanPayUtil;
import com.akk.module.cjpay.utils.RSA;
import com.akk.module.hlbpay.util.HlbBeanUtils;
import com.akk.module.hxt.utils.HxtUtils;
import com.akk.utils.RestResponse;
import com.akk.utils.rsa.RSAUtils;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

@Component
public class AvsCjPayBusiness {


    @Autowired
    private CjPayService cjPayService;

    @Autowired
    private AvsPayOrderService orderService;
    @Autowired
    private AvsCustomerService customerService;
    @Autowired
    private AccessService accessService;

    @Value("${server.url}")
    private String serverUrl;

    // 直接支付
    public RestResponse payment(String payerId,String orderNum,String accessBind){
        List<AvsPayOrder> orders = orderService.findByOrderNum(orderNum);
        if (orders.isEmpty())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"订单号不存在");
        AvsCustomer customer = customerService.findByCustomerId(payerId);
        if (customer == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"用户信息不存在");
        if (!orders.get(0).getPayerId().equals(customer.getCustomerId()))
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"非法请求");
        AccessBind cashBind = accessService.findAccessBindById(accessBind);
        if (cashBind == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"银行卡信息不存在");
        AvsPayOrder order = orders.get(0);
        order.setPayBank(cashBind.getCardName());
        order.setPayCardNo(cashBind.getCardNum());
        orderService.update(order);
        CjpayDirectPaymentRequest request = new CjpayDirectPaymentRequest();
        request.setBkAcctTp(cashBind.getCardType().equals("J")?"01":"00");
        request.setBkAcctNo(ChanPayUtil.encrypt(cashBind.getCardNum(),PayConstants.CJ_MERCHANT_PUBLIC_KEY,PayConstants.CJ_CHARSET));
        request.setIDNo(ChanPayUtil.encrypt(customer.getIdCard(),PayConstants.CJ_MERCHANT_PUBLIC_KEY,PayConstants.CJ_CHARSET));
        request.setCstmrNm(ChanPayUtil.encrypt(cashBind.getHoldName(),PayConstants.CJ_MERCHANT_PUBLIC_KEY,PayConstants.CJ_CHARSET));
        request.setMobNo(ChanPayUtil.encrypt(cashBind.getPhone(),PayConstants.CJ_MERCHANT_PUBLIC_KEY,PayConstants.CJ_CHARSET));
        if (cashBind.getCardType().equals("X")){
            String date = RSAUtils.decryptDataOnJava(cashBind.getValidity(),PayConstants.CARD_RSA_PRIVATE_KEY_PKCS8);
            if (!date.isEmpty())
                date = date.substring(0,2) + "/" + date.substring(2,4);
            request.setCardCvn2(ChanPayUtil.encrypt(RSAUtils.decryptDataOnJava(cashBind.getCvv2(), PayConstants.CARD_RSA_PRIVATE_KEY_PKCS8),PayConstants.CJ_MERCHANT_PUBLIC_KEY,PayConstants.CJ_CHARSET));
            request.setCardExprDt(ChanPayUtil.encrypt(date,PayConstants.CJ_MERCHANT_PUBLIC_KEY,PayConstants.CJ_CHARSET));
        }
        request.setIDTp("01");
        request.setReturnUrl(serverUrl+"/pay/cash.html?payerId="+payerId+"&appId="+customer.getAppId());
        request.setNotifyUrl(serverUrl+"/thmlfApi/avs/cjpay/paymentNotify");
        request.setTrxId(orderNum);
        request.setOrdrName(orders.get(0).getRemark());
        request.setOrdrDesc("[{\"name\":\""+orders.get(0).getRemark()+"\"}]");
        request.setMerUserId(payerId);
        request.setTrxAmt(orders.get(0).getAmountTotal().toString());
        RestResponse restResponse = cjPayService.directPayment(request);
        return restResponse;
    }

    // 支付通知
    public String paymentNotify(CjpayNotifyRequest request) {
        List<AvsPayOrder> orders = orderService.findByOrderNum(request.getOuter_trade_no());
        if (orders.isEmpty())
            return "error";
        AvsPayOrder order = orders.get(0);
        System.out.println("通知》》："+new Gson().toJson(request));
        if (request.getTrade_status().equals("TRADE_SUCCESS")){
            order.setStatus(Enums.OrderStatusEnum.SUCCESS_PAYED.getValue());
        }else if (request.getTrade_status().equals("TRADE_CLOSED")){
            order.setStatus(Enums.OrderStatusEnum.FAILED.getValue());
        }
        if (order.getRemark().equals(PayConstants.VIP_CASH)){
            order.setStatus(Enums.OrderStatusEnum.VIP_SUCCESS.getValue());
        }
        orderService.update(order);
        // TRADE_CLOSED  失败
        return "success";
    }

    // 查询绑卡
    public RestResponse bindCardQuery(String payerId, String orderNum, String accessBind) {
        List<AvsPayOrder> orders = orderService.findByOrderNum(orderNum);
        if (orders.isEmpty())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"订单号不存在");
        AvsCustomer customer = customerService.findByCustomerId(payerId);
        if (customer == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"用户信息不存在");
        if (!orders.get(0).getPayerId().equals(customer.getCustomerId()))
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"非法请求");
        AccessBind cashBind = accessService.findAccessBindById(accessBind);
        if (cashBind == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"银行卡信息不存在");
        CJpayBindCardQueryRequest request = new CJpayBindCardQueryRequest();
        request.setMerUserId(payerId);
        request.setCardEnd(cashBind.getLastFourNum());
        request.setCardBegin(cashBind.getCardNum().substring(0,6));
        request.setTrxId(orderNum);
        return cjPayService.bindCardQuery(request);
    }

    // 绑卡
    public RestResponse bindCard(String payerId, String orderNum, String accessBind) {
        List<AvsPayOrder> orders = orderService.findByOrderNum(orderNum);
        if (orders.isEmpty())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"订单号不存在");
        AvsCustomer customer = customerService.findByCustomerId(payerId);
        if (customer == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"用户信息不存在");
        if (!orders.get(0).getPayerId().equals(customer.getCustomerId()))
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"非法请求");
        AccessBind cashBind = accessService.findAccessBindById(accessBind);
        if (cashBind == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"银行卡信息不存在");
        CjpayBindCardRequest request = new CjpayBindCardRequest();
        request.setTrxId(orderNum);
        request.setExpiredTime("10m");
        request.setMerUserId(payerId);
        request.setExtension("[{'accessBind':'"+accessBind+"','amount':'"+orders.get(0).getAmountTotal()+"'}]");
        request.setReturnUrl(serverUrl+"/thmlfApi/avs/cjpay/returnUrl");
        return cjPayService.bindCard(request);
    }

    // 返回地址
    public String returnUrl(String status, String payerId, String orderNum, String accessBind,String amount, HttpServletResponse response) {
        try {
            response.sendRedirect(serverUrl+"/pay/cjpay.html?payerId="+payerId+"&orderNum="+orderNum+"&gateway=cjpay&amount="+amount);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}
